import type { ISectionDetails } from '@/interfaces';
import { useEffect, useRef, useState } from 'react';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import classNames from 'classnames';
import useToast from '@/hooks/useToast';
import { useMutation } from '@tanstack/react-query';
import { updateSectionContent } from '@/services/api';
import ContentHtml from '@/app/[locale]/common/content/html';
import { getEditorContentHtml, setEditorContentHtml } from '@/lib/editor';
import {
  handleEditorBeforeunload,
  handleEditorSave,
  handleEditorStatusChanges,
} from '@/lib/editor/handle';
import dynamic from 'next/dynamic';
import EditorSuspense from '@/app/[locale]/posts/[id]/edit/editor/load';
import ToggleProperties from '@/app/[locale]/admin/common/toggle-properties';
import type { PrefixedTTranslatedFields } from '@/lib/dictionaries';

const DynamicEditor: any = dynamic(
  () => import('../../../../posts/[id]/edit/editor/editor'),
  {
    loading: () => <EditorSuspense />,
    ssr: false,
  },
);

export default function QuerySectionContent({
  details,
  translatedFields,
}: {
  details: ISectionDetails;
  translatedFields: PrefixedTTranslatedFields<'sectionAdminPage'>;
}) {
  const [previewContent, setPreviewContent] = useState(details.content || '');
  const { show } = useToast();
  const editorRef = useRef<any>();
  const [isActive, setIsActive] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const isDirty = useRef(false);
  const isLoadingSave = useRef(false);
  const [isReady, setIsReady] = useState(false);
  const [tabIndex, setTabIndex] = useState(0);

  const updateSectionContentMutation = useMutation(updateSectionContent);

  useEffect(() => {
    const selector = document.querySelector('.yw-navbar-layout');
    if (selector) {
      selector.classList.remove('sticky-top');
    }

    return () => {
      if (selector) {
        selector.classList.add('sticky-top');
      }
    };
  }, []);

  function getContent(data?: any) {
    return getEditorContentHtml(editorRef.current, data);
  }

  async function onClickSave() {
    const editor = editorRef.current;
    if (!editor) {
      show({
        type: 'DANGER',
        message: '编辑器不存在',
      });
      return;
    }

    await handleEditorSave({
      editor,
      isDirty,
      setIsActive,
      setIsSaving,
      callback: onClickSaveCore,
    });
  }

  async function onClickSaveCore({
    data,
    reset,
  }: {
    data: string;
    reset: () => void;
  }) {
    try {
      isLoadingSave.current = true;

      const content = getContent(data);
      if (!content) {
        show({
          type: 'SUCCESS',
          message: '保存完成',
        });
        return;
      }

      await updateSectionContentMutation.mutateAsync({
        id: details.basic.id,
        data: {
          content,
        },
      });

      show({
        type: 'SUCCESS',
        message: '保存完成',
      });
    } catch (e) {
      updateSectionContentMutation.reset();
      show({
        type: 'DANGER',
        message: e,
      });
    } finally {
      isLoadingSave.current = false;
      reset();
    }
  }

  async function onClickPreview() {
    setTabIndex(0);
    setPreviewContent(getContent());
  }

  async function onClickLoadEditor() {
    setTabIndex(1);
  }

  function onReady({ editor }: { editor: any }) {
    handleEditorStatusChanges({
      editor,
      isDirty,
      setIsActive,
      setIsSaving,
    });
    handleEditorBeforeunload({ editor });
    setEditorContentHtml(editor, details.content);
    editorRef.current = editor;
    setIsReady(true);
  }

  return (
    <div className="card">
      <div className="card-header bg-transparent text-secondary">
        <i className="bi bi-card-text me-2"></i>
        {translatedFields.detailPage.QuerySectionContent.content}
      </div>
      <div className="card-body vstack gap-4">
        <ToggleProperties
          navClasss="ms-2"
          isTable={false}
          tabIndex={tabIndex}
          items={[
            {
              index: 0,
              name: translatedFields.detailPage.QuerySectionContent.preview,
              icon: 'bi-book',
              callback: onClickPreview,
            },
            {
              index: 1,
              name: translatedFields.detailPage.QuerySectionContent.edit,
              icon: 'bi-pencil-square',
              callback: onClickLoadEditor,
            },
            {
              index: 2,
              name: translatedFields.detailPage.QuerySectionContent.save,
              icon: 'bi-save',
              callback: onClickSave,
              isLoading: updateSectionContentMutation.isLoading,
            },
          ]}
        />

        <div className={classNames(tabIndex === 1 ? 'd-block' : 'd-none')}>
          <DynamicEditor
            id={details.basic.id}
            type="section"
            onReadyCallback={onReady}
          />
        </div>

        {tabIndex === 0 &&
          (previewContent && previewContent !== 'nodata' ? (
            <ContentHtml content={previewContent} />
          ) : (
            <Nodata />
          ))}
      </div>
    </div>
  );
}
